package product

import (
	"fmt"
	"woo-server/coms/structs"
	"woo-server/coms/utils"
	"woo-server/models/db"
	"woo-server/models/db/content"
)

// 商品字段表
type Product struct {
	*structs.Common    `gorm:"-" json:"-"`
	ProductId          uint64               `gorm:"primary_key;AUTO_INCREMENT;column:product_id;"` // 自增主键
	CategoryId         uint64               `gorm:"column:category_id;size:255;"`                  // 分类ID
	FileId             uint64               `gorm:"column:image_id;size:255;"`                     // 图片ID
	ProductName        string               `gorm:"column:product_name;size:255;"`                 // 商品名称
	Describe           string               `gorm:"column:describe;size:255;"`                     // 商品卖点
	SpecType           uint                 `gorm:"column:spec_type;size:50;"`                     // 商品规格(10单规格 20多规格)
	Content            string               `gorm:"column:content;"`                               // 商品详细
	ProductPrice       uint                 `gorm:"column:product_price;size:255;"`                // 商品价格
	ProductSales       uint                 `gorm:"column:product_sales;"`                         // 销量
	OpenGradeDiscount  uint                 `gorm:"column:open_grade_discount;size:255;"`          // 是否开启会员折扣(1开启 0关闭)
	AloneGradeDiscount uint                 `gorm:"column:alone_grade_discount;"`                  // 会员折扣设置(0默认等级折扣 1单独设置折扣)
	OpenPointsDiscount uint                 `gorm:"column:open_points_discount;size:255;"`         // 会否开启积分抵扣
	PointsRule         uint                 `gorm:"column:points_rule;"`                           // 积分规则{'points'1000,'price':100} 1000积分抵扣100元
	PointsGift         uint                 `gorm:"column:points_gift;size:255;"`                  // 赠送积分
	StockNum           uint                 `gorm:"column:stock_num;"`                             // 当前库存数量
	DeliveryId         uint                 `gorm:"column:delivery_id;size:255;"`                  // 配送模板id
	ProductSort        uint                 `gorm:"column:product_sort;"`                          // 商品排序
	ProductStatus      uint                 `gorm:"column:product_status;size:255;"`               // 商品状态(10上架 20下架)
	IsDelete           uint                 `gorm:"column:is_delete;"`                             // 是否删除(0:正常 1:删除)
	Image              []content.UploadFile `gorm:"foreignKey:FileId;references:FileId"`           // 图片模型数组返回
	Category           ProductCategory      `gorm:"foreignKey:CategoryId"`                         // 分类模型返回
	db.Basics
}

// 表名
func (s *Product) TableName() string {
	return "woo_product"
}

// 初始化
func NewProduct(com *structs.Common) *Product {
	d := &Product{}
	return d
}

func (s *Product) GetConfig() structs.CFConfig {
	list := structs.CFConfig{}
	list.Column = s.Column()
	list.Forms = s.Forms()
	return list
}

func (s *Product) Column() []structs.ColumnCommon {
	result := make([]structs.ColumnCommon, 0)
	result = append(result, structs.ColumnCommon{Title: "ID", DataIndex: "productId"})
	result = append(result, structs.ColumnCommon{Title: "封面", DataIndex: "Image"})
	result = append(result, structs.ColumnCommon{Title: "标题", DataIndex: "ProductName"})
	result = append(result, structs.ColumnCommon{Title: "分类", DataIndex: "Category.Name"})
	result = append(result, structs.ColumnCommon{Title: "商品类型", DataIndex: "ShowType"})
	result = append(result, structs.ColumnCommon{Title: "排序", DataIndex: "Sort"})
	result = append(result, structs.ColumnCommon{Title: "更新时间", DataIndex: "UpdateDate"})
	result = append(result, structs.ColumnCommon{Title: "操作", DataIndex: "Operation"})
	return result
}

func (s *Product) Forms() []structs.FormsCommon {
	result := make([]structs.FormsCommon, 0)

	gModel := NewProductCategory(s.Common)
	_, options := gModel.GetAllCategory()
	result = append(result, structs.FormsCommon{Key: "ProductId", Label: "主键ID", Type: "hidden", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "CategoryId", Label: "分类", Type: "select", Options: gModel.SetOption(options, 0)})
	result = append(result, structs.FormsCommon{Key: "FileId", Label: "封面", Type: "onlyUploadImage", Options: "Image"})
	result = append(result, structs.FormsCommon{Key: "ProductName", Label: "标题", Type: "input", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "ShowType", Label: "商品类型", Type: "radio", Options: []map[string]interface{}{{"Value": 20, "Name": "大图"}, {"Value": 10, "Name": "小图"}}})
	result = append(result, structs.FormsCommon{Key: "AloneGradeDiscount", Label: "商品规格", Type: "FreeBlockSelect", Options: []map[string]interface{}{{"Value": 10, "Name": "单规格"}, {"Value": 20, "Name": "多规格"}}})
	result = append(result, structs.FormsCommon{Key: "ProductPrice", Label: "商品价格", Type: "input", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "Content", Label: "商品详细", Type: "markdown", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "ProductSort", Label: "排序", Type: "number", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "SpecType", Label: "会员折扣", Type: "radio", Options: []map[string]interface{}{{"Value": 1, "Name": "开启"}, {"Value": 0, "Name": "关闭"}}})
	result = append(result, structs.FormsCommon{Key: "OpenPointsDiscount", Label: "积分抵扣", Type: "input", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "PointsRule", Label: "积分规则", Type: "input", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "PointsGift", Label: "赠送积分", Type: "input", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "StockNum", Label: "库存数量", Type: "input", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "DeliveryId", Label: "配送模板", Type: "input", Options: []string{}})
	result = append(result, structs.FormsCommon{Key: "ProductStatus", Label: "状态", Type: "switch", Options: []string{}})
	return result
}

// 创建
func (s *Product) Create() error {
	return utils.GORM.Debug().Table(s.TableName()).Create(s).Error
}

// 批量创建
func (s *Product) BatchCreate(data []*Product) error {
	return utils.GORM.Debug().Table(s.TableName()).Create(data).Error
}

// 获取分页列表及总数
func (s *Product) GetListAndTotal(search string, page int, pageSize int) ([]*Product, int64) {
	list := make([]*Product, 0)
	var total int64 = 0
	// 查询
	query := utils.GORM.Debug().Table(s.TableName())
	query = query.Where("is_delete = 0").Order("product_sort asc")
	if len(search) > 0 {
		search = fmt.Sprintf("%%%s%%", search)
		query = query.Where("product_title = ?", search)
	}

	// 总数
	query.Count(&total)

	// 列表
	offset := (page - 1) * pageSize
	query.Preload("Image").Preload("Category").Limit(pageSize).Offset(offset).Find(&list)

	return list, total
}

// 获取单数据
func (s *Product) GetFirst(where string, field int) *Product {
	//info := make([]*Product, 0)

	// 查询
	query := utils.GORM.Debug().Table(s.TableName())

	query = query.Where(where, field)

	query.Preload("Image").First(&s)
	return s
}

// 获取商品分类
func (s *Product) GetCategory(where string, field []int) []Product {
	list := make([]Product, 0)

	// 查询
	query := utils.GORM.Debug().Table(s.TableName())
	query = query.Order("sort asc")
	query = query.Where(where, field)

	query.Find(&list)
	return list
}

// 更新商品
func (s *Product) Save() error {
	// 更新
	return utils.GORM.Debug().Table(s.TableName()).Save(s).Error
}

// 删除商品
func (s *Product) Delete() error {
	return utils.GORM.Debug().Table(s.TableName()).Delete(s).Error
}

// 删除商品
func (s *Product) SetDelete() error {
	return utils.GORM.Debug().Table(s.TableName()).Where("product_id = ?", s.ProductId).Update("is_delete", 1).Error
}

// 获取单条数据
func (s *Product) First() error {
	return utils.GORM.Debug().Table(s.TableName()).First(s).Error
}
